const crypto=require('crypto');
const events=require('events');
const router=require('koa-router')();
const koaBody=require('koa-body');
const User=require('../models/index').User;
const checkNotLogin=require('../middlewares/checkNotLogin');

router.get('/',checkNotLogin(),async ctx=>{
    await ctx.render('login',{
        title:'Login',
        success:ctx.flash.success,
        error:ctx.flash.error,
        refer:ctx.query.refer
    });
});

router.post('/',checkNotLogin(),koaBody(),async ctx=>{
    let {body}=ctx.request,loginUser=await User.findOne({name:body.name}),ee=new events();

    ee.on('fail',(msg='用户名或密码错误')=>{
        ctx.flash={error:msg};
        ctx.redirect('back');
    });

    if(!loginUser)return ee.emit('fail');
    if(crypto.createHash('md5').update(body.password).digest('hex')!==loginUser.password)return ee.emit('fail');

    ctx.session.loginUser={
        _id:loginUser._id,
        name:loginUser.name,
        email:loginUser.email,
        avatar:loginUser.avatar,
        score:loginUser.score,
        intro:loginUser.intro
    };

    ctx.flash={success:'登录成功'};
    ctx.redirect(body.refer?body.refer:'/');
});

module.exports=router;